import { EEquipmentType, EItemType, IItem, isEquipment, EItemQuality } from "../Item/Item";
import { Equipment, IEquipment } from "../Item/Equipment";
import { Gem } from "../Item/Gem";

// BagManager.ts 处理添加删除物品
export class BagManager {
    private items: IItem[] = [];
    
    // 添加物品
    addItem(item: IItem) {
        // 检查是否可堆叠
        const stackableItem = this.items.find(i => 
            i.id === item.id && i.stackable
        );
        
        if (stackableItem) {
            stackableItem.count += item.count || 1;
        } else {
            this.items.push(item);
        }
    }

    // 移除物品
    removeItem(item: IItem, count: number = 1): boolean {
        if (!item || !item.uid) {
            console.warn("尝试删除的物品无效:", item);
            return false;
        }

        const index = this.items.findIndex(i => i.uid === item.uid);
        if (index === -1) {
            console.warn("尝试删除不存在的物品:", item);
            return false;
        }

        const existingItem = this.items[index];
        
        // 处理堆叠物品
        if (existingItem.stackable && existingItem.count > 1) {
            if (existingItem.count > count) {
                // 减少数量
                existingItem.count -= count;
                console.log(`减少物品数量: ${existingItem.name} 剩余 ${existingItem.count}`);
                return true;
            } else if (existingItem.count === count) {
                // 完全移除
                this.items.splice(index, 1);
                console.log(`完全移除物品: ${existingItem.name}`);
                return true;
            } else {
                // 数量不足
                console.warn(`物品数量不足: ${existingItem.name} 只有 ${existingItem.count}, 尝试移除 ${count}`);
                return false;
            }
        } else {
            // 非堆叠物品或数量为1
            this.items.splice(index, 1);
            console.log(`移除物品: ${existingItem.name}`);
            return true;
        }
    }

    removeAllItems() {
        this.items = [];
    }

    getItemByUid(uid: string): IItem | null {
        return this.items.find(item => item.uid === uid) || null;
    }
    
    // 获取所有物品可操作对象，例如Equipment
    getItems(): IItem[] {
        return this.items;
    }
    
    // 设置物品，
    setItems(items: IItem[]) {
        this.items = items || [];
    }

    // 将对象实例处理为序列化数据{}
    getPackage(): any[] {
        return this.items.map(item => {
            if (item instanceof Equipment) {
                return item.getPackage(); // 使用装备的序列化方法
            } else if (item instanceof Gem) {
                return (item as Gem).getPackage(); // 宝石的序列化方法
            } else {
                return item; // 基础物品直接返回
            }
        });
    }

    // 处理反序列化，创建对象实例
    setPackage(itemsData: any[]): void {
        this.items = [];

        for (const itemData of itemsData || []) {
            if (!itemData) continue;
            
            // 根据 itemType 创建正确的对象实例
            if (itemData.itemType === EItemType.Equipment) {
                const equipment = new Equipment({
                    id: itemData.id,
                    uid: itemData.uid,
                    itemType: itemData.itemType,
                    name: itemData.name,
                    count: itemData.count,
                    icon: itemData.icon,
                    desc: itemData.desc,
                    quality: itemData.quality,
                    price: itemData.price,
                    equipmentType: itemData.equipmentType,
                    gemSlots: itemData.gemSlots,
                    profession: itemData.profession,
                    affixes: itemData.affixes,
                    affixes_wuxing: itemData.affixes_wuxing,
                    gems: itemData.gems,
                    level: itemData.level,
                    isEquipped: itemData.isEquipped,
                    score: itemData.score,
                    wuxing: itemData.wuxing
                });
                this.items.push(equipment);

            } else if (itemData.itemType === EItemType.Gem) {
                // 类似处理宝石
                const gem = new Gem(itemData);
                this.items.push(gem);
            } else {
                // 基础物品直接存储
                this.items.push(itemData);
            }
        }
    }

    // 获取所有装备（使用类型守卫）
    getEquipmentItems(): IEquipment[] {
        return this.items.filter(isEquipment);
    }

    // 获取非装备物品
    getOtherItems(): IItem[] {
        return this.items.filter(item => item.itemType !== EItemType.Equipment);
    }

    // 获取特定类型的装备
    getEquipmentByType(equipmentType: EEquipmentType): IEquipment[] {
        return this.items.filter(item => 
            isEquipment(item) && item.equipmentType === equipmentType
        ) as IEquipment[];
    }

    /**
     * 根据品质集合获取装备
     * @param qualities 品质集合 Set<EItemQuality>
     * @returns 符合条件的装备列表
     */
    getEquipmentsByQualities(qualities: Set<EItemQuality>): IEquipment[] {
        if (!qualities || qualities.size === 0) {
            return [];
        }
        // 复用 getEquipmentItems 确保类型安全，然后过滤品质
        return this.getEquipmentItems().filter(item => qualities.has(item.quality));
    }
}